/*
 * This file is an example of how to embed web-server functionality
 * into existing application.
 * Compilation line:
 * cc example.c shttpd.c -DEMBEDDED -DMT
 */

#ifdef _WIN32
#include <winsock.h>
#define	snprintf		_snprintf
#define	sleep(x)		Sleep((x) * 1000)	
#pragma comment(lib,"ws2_32")
#else
#include <sys/types.h>
#include <sys/select.h>
#include <unistd.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "shttpd.h"

static int
index_html(struct shttpd_callback_arg *arg)
{
	int	i;

	/* Output HTTP headers */
	shttpd_printf(arg->connection, "%s\r\n", "HTTP/1.1 200 OK");
	shttpd_printf(arg->connection, "%s\r\n", "Content-Type: text/plain");
	shttpd_printf(arg->connection, "%s\r\n", "");

	sleep(2);

	/* Output large chunk of binary data */
	for (i = 0; i < 100000; i++)
		shttpd_printf(arg->connection, "%s\n", "ABCDEFGHIJKLMNOP");
	
	return (0);	/* Not used */
}

int main(int argc, char *argv[])
{
	int		sock1, sock2, data = 1234567;

	/* Get rid of warnings */
	argc = argc;
	argv = argv;
	
	/* Initialize and setup URLs we gonna serve */
	shttpd_init(NULL);

	/* Let pass 'data' variable to callback, user can change it */
	shttpd_register_url("/", &index_html, (void *) &data);

	/* Open two listening sockets */
	sock1 = shttpd_open_port(9002);
	sock2 = shttpd_open_port(9001);

	/*
	 * Serve connections infinitely until someone kills us
	 * XXX it would be better to select() on sock1 and sock2 here,
	 * but let's make it simple and stupid for now.
	 */
	for (;;)
		shttpd_poll(sock1, 1200), shttpd_poll(sock2, 1200);

	/* Probably unreached, because we will be killed by signal */
	shttpd_fini();

	return (EXIT_SUCCESS);
}
